package com.yj.ccs.abs.util.file;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * Copyright 2018 (C) Yunjian-VC
 * Created on : 2018/1/30
 * Author     : Unbelievable9
 **/
public class CustomMultipartFile implements MultipartFile {

    private final byte[] fileContent;

    private String fileName;

    private String contentType;

    private File file;

    private String destPath = System.getProperty("java.io.tmpdir");

    private FileOutputStream fileOutputStream;

    public CustomMultipartFile(byte[] fileData, String name) {
        this.fileContent = fileData;
        this.fileName = name;

        file = new File(destPath + fileName);
    }

    @Override
    public String getName() {
        return fileName;
    }

    @Override
    public String getOriginalFilename() {
        return fileName;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return file != null;
    }

    @Override
    public long getSize() {
        return file.getTotalSpace();
    }

    @Override
    public byte[] getBytes() throws IOException {
        return fileContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(fileContent);
    }

    @Override
    public void transferTo(File file) throws IOException, IllegalStateException {
        fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(fileContent);
    }
}
